package net.ufrog.common.weixin.pojos;

import java.io.IOException;
import java.io.Serializable;
import java.util.Properties;

import net.ufrog.common.exception.ServiceException;
import net.ufrog.common.utils.Files;
import net.ufrog.common.utils.Strings;

import com.alibaba.fastjson.annotation.JSONField;

/**
 * 错误
 * 
 * @author ultrafrog
 * @version 1.0, 2014-12-29
 * @since 1.0
 */
public class Err implements Serializable {

	private static final long serialVersionUID = 3600356346586243109L;
	
	/**  */
	private static Properties errors;

	/** 代码 */
	@JSONField(name = "errcode")
	private String code;
	
	/** 消息 */
	@JSONField(name = "errmsg")
	private String msg;
	
	/**
	 * 读取代码
	 * 
	 * @return
	 * @see #code
	 */
	public String getCode() {
		return code;
	}

	/**
	 * 设置代码
	 * 
	 * @param code
	 * @see #code
	 */
	public void setCode(String code) {
		this.code = code;
	}

	/**
	 * 读取消息
	 * 
	 * @return
	 * @see #msg
	 */
	public String getMsg() {
		return msg;
	}

	/**
	 * 设置消息
	 * 
	 * @param msg
	 * @see #msg
	 */
	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	/**
	 * 读取消息<br>
	 * 中文翻译
	 * 
	 * @return
	 */
	public String getMessage() {
		if (Strings.empty(code)) return null;
		if (errors == null) {
			try {
				errors = new Properties();
				errors.load(Files.getInputStream("/weixin-errors.properties"));
			} catch (IOException e) {
				throw new ServiceException(e.getMessage(), e);
			}
		}
		return errors.getProperty(code);
	}
	
	/**
	 * 处理是否成功
	 * 
	 * @return
	 */
	public Boolean success() {
		return (Strings.empty(code) || Strings.equals("0", code));
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		if (Strings.empty(code)) return super.toString();
		return getMessage() + "(code: " + code + ")";
	}
}
